from openai import OpenAI
from config import LLM_API_KEY, LLM_API_MODEL, LLM_API_URL, PROMPT_NAME
from typing import Any, List
from logger import logger_main
from utils import retry_on_failure
client = OpenAI(
    api_key=LLM_API_KEY,
    base_url=LLM_API_URL
)

prompt = ""

with open(f"prompt/{PROMPT_NAME}.md") as f:
    prompt = f.read()
    logger_main.info(f"已加载{PROMPT_NAME}.MD提示词文件。")


@retry_on_failure()
def generate_text(message: List[Any]) -> str:
    # 确保消息列表的最后一项是 user 角色
    # 移除尾部所有的 assistant 消息
    filtered_message = message.copy()
    while filtered_message and filtered_message[-1].get("role") == "assistant":
        filtered_message.pop()
    if len(filtered_message) == 0:
        raise ValueError("消息列表中没有用户消息")
    response = client.chat.completions.create(
        model=LLM_API_MODEL,
        messages=[
            {"role": "system", "content": prompt},
            *filtered_message
        ]
    )
    reply = response.choices[0].message.content
    if reply is None:
        raise ValueError("LLM 返回了空回复")
    return reply.replace("**", "").replace("`", "")


if __name__ == "__main__":
    print(generate_text([{
        "role": "user",
        "content": [{
            "type": "text",
            "text": f"Handsomedog邀请你加入了群聊，群聊参与人还有：Sittymin、MULUAN、Z、王博源秘书、达瓦里氏_源、ST470"
        },
            {
            "type": "text",
            "text": f"[系统通知]你收到了一条群聊邀请信息，邀请人的用户名称为:`Handsomedog`。（此消息为自动注入，请不要回复）"
        }]
    }]))
